#include "Reactor.hpp"
#include "Listener.hpp"
#include "Protocol.hpp"
#include "Socket.hpp"
#include "NetCal.hpp"

#include <iostream>
#include <memory>

using namespace SocketModule;

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "格式错误: ./epollServer port" << std::endl;
        exit(1);
    }

    int port = std::stoi(argv[1]);

    std::shared_ptr<NetCal> c = std::make_shared<NetCal>();
    
    std::shared_ptr<Protocol> pro = std::make_shared<Protocol>([&c](Request& req)->Response
    {
        return c->cal(req);       
    });    

    std::shared_ptr<Connection> conn = std::make_shared<Listener>(port);
    conn->registerHandler([&pro](std::string& inbuf)->std::string
    {
        LOG(LogLevel::DEBUG) << "handler excute";
        std::string response_str;
        while (true)
        {
            std::string package;
            if (Protocol::decode(inbuf, package) == false)
            {
                break;
            }

            response_str += pro->excute(package);
        }
        LOG(LogLevel::DEBUG) << "handler return response_str:" << response_str;
        return response_str;
    });

    std::unique_ptr<Reactor> R = std::make_unique<Reactor>();
    R->addConnection(conn);
    R->loop();

    return 0;
}
